package com.ruoyi.web.core.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;

/**
 * <pre>
 *
 *
 * </pre>
 *
 * @author: zhangli
 * @since: 2022/7/26 0026
 */
@Slf4j
@Component
public class HttpClient {


    public String doGet(String url) {
        return doGet(url, "utf-8");
    }


    public String doGet(String url, Map<String, String> headers) {
        return doGet(url, "utf-8", headers);
    }

    /**
     * httpClient的get请求方式
     * 使用GetMethod来访问一个URL对应的网页实现步骤：
     * 1.生成一个HttpClient对象并设置相应的参数；
     * 2.生成一个GetMethod对象并设置响应的参数；
     * 3.用HttpClient生成的对象来执行GetMethod生成的Get方法；
     * 4.处理响应状态码；
     * 5.若响应正常，处理HTTP响应内容；
     * 6.释放连接。
     *
     * @param url
     * @param charset
     * @return
     */
    public String doGet(String url, String charset) {
        //1.生成HttpClient对象并设置参数
        org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();


        //设置Http连接超时为5秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        //2.生成GetMethod对象并设置参数
        GetMethod getMethod = new GetMethod(url);
        //设置get请求超时为5秒
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
        //设置请求重试处理，用的是默认的重试处理：请求三次
        // getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        String response = "";
        //3.执行HTTP GET 请求
        try {
            int statusCode = httpClient.executeMethod(getMethod);
            //4.判断访问的状态码
            if (statusCode != HttpStatus.SC_OK) {
                log.error("请求出错：" + getMethod.getStatusLine());
            }
            //5.处理HTTP响应内容
            //HTTP响应头部信息，这里简单打印
//            Header[] headers = getMethod.getResponseHeaders();
//            for (Header h : headers) {
//                System.out.println(h.getName() + "---------------" + h.getValue());
//            }
            //读取HTTP响应内容，这里简单打印网页内容
            //读取为字节数组
            byte[] responseBody = getMethod.getResponseBody();
            response = new String(responseBody, charset);
            log.info("-----------response:" + response);
            //读取为InputStream，在网页内容数据量大时候推荐使用
            //InputStream response = getMethod.getResponseBodyAsStream();
        } catch (HttpException e) {
            //发生致命的异常，可能是协议不对或者返回的内容有问题
            System.out.println("请检查输入的URL!");
            log.error(e.getMessage(), e);
        } catch (IOException e) {
            //发生网络异常
            System.out.println("发生网络异常!");
            log.error(e.getMessage(), e);
        } finally {
            //6.释放连接
            getMethod.releaseConnection();
        }
        return response;
    }

    public String doGet(String url, String charset, Map<String, String> headers) {
        //1.生成HttpClient对象并设置参数
        org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();


        //设置Http连接超时为5秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        //2.生成GetMethod对象并设置参数
        GetMethod getMethod = new GetMethod(url);

        headers.entrySet().forEach(entry -> getMethod.addRequestHeader(entry.getKey(), entry.getValue()));

        //设置get请求超时为5秒
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
        //设置请求重试处理，用的是默认的重试处理：请求三次
        // getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        String response = "";
        //3.执行HTTP GET 请求
        try {
            int statusCode = httpClient.executeMethod(getMethod);
            //4.判断访问的状态码
            if (statusCode != HttpStatus.SC_OK) {
                log.error("请求出错：" + getMethod.getStatusLine());
            }
            //5.处理HTTP响应内容
            //HTTP响应头部信息，这里简单打印
//            Header[] headers = getMethod.getResponseHeaders();
//            for (Header h : headers) {
//                System.out.println(h.getName() + "---------------" + h.getValue());
//            }
            //读取HTTP响应内容，这里简单打印网页内容
            //读取为字节数组
            byte[] responseBody = getMethod.getResponseBody();
            response = new String(responseBody, charset);
            log.info("-----------response:" + response);
            //读取为InputStream，在网页内容数据量大时候推荐使用
            //InputStream response = getMethod.getResponseBodyAsStream();
        } catch (HttpException e) {
            //发生致命的异常，可能是协议不对或者返回的内容有问题
            System.out.println("请检查输入的URL!");
            log.error(e.getMessage(), e);
        } catch (IOException e) {
            //发生网络异常
            System.out.println("发生网络异常!");
            log.error(e.getMessage(), e);
        } finally {
            //6.释放连接
            getMethod.releaseConnection();
        }
        return response;
    }

    public String doPost(String url, JSONObject json) {
        boolean useProxy = false;

        return doPost(url, json, new HashMap<>());
    }

    /**
     * post请求
     *
     * @param url
     * @param json
     * @return
     */
    public String doPost(String url, JSONObject json, Map<String, String> headers) {
        org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
        PostMethod postMethod = new PostMethod(url);

        try {
            RequestEntity requestEntity = new StringRequestEntity(json.toString(), "application/json", "UTF-8");

            postMethod.addRequestHeader("accept", "*/*");
            postMethod.addRequestHeader("connection", "Keep-Alive");
            //设置json格式传送
            postMethod.addRequestHeader("Content-Type", "application/json;charset=UTF-8");
            //必须设置下面这个Header
            postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");

            headers.entrySet().forEach(entry -> postMethod.addRequestHeader(entry.getKey(), entry.getValue()));

            //添加请求参数
            postMethod.setRequestEntity(requestEntity);

            String res = "";

            int code = httpClient.executeMethod(postMethod);
            if (code == 200) {
                res = postMethod.getResponseBodyAsString();
                log.info(res);
            }
            return res;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }

        return "";
    }

    public String doPostForm(String url, Map<String, String> params, Map<String, String> headers) {
        log.info("http 请求!!! url:{}", url);
        log.info("http 请求body!!! body:{}", params);
        org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
        PostMethod postMethod = new PostMethod(url);

        try {
            List<NameValuePair> nameValuePairs = new ArrayList();
            if (params.size() != 0) {
                Set keySet = params.keySet();
                Iterator it = keySet.iterator();

                while (it.hasNext()) {
                    String k = it.next().toString();
                    String v = (String) params.get(k);
                    nameValuePairs.add(new NameValuePair(k, v));
                }
            }

            postMethod.addRequestHeader("accept", "*/*");
            postMethod.addRequestHeader("connection", "Keep-Alive");
            postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
            postMethod.setRequestBody((NameValuePair[]) nameValuePairs.toArray(new NameValuePair[0]));

            headers.entrySet().forEach(entry -> postMethod.addRequestHeader(entry.getKey(), entry.getValue()));

            String res = "";
            int code = httpClient.executeMethod(postMethod);
            if (code == 200) {
                res = postMethod.getResponseBodyAsString();
                log.info("response: {}", res);
            }

            return res;
        } catch (IOException var9) {
            var9.printStackTrace();
            return "";
        }
    }

}
